package admin

import (
	"context"
	"encoding/json"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type RoleListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleListLogic {
	return &RoleListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RoleListLogic) RoleList(req *types.Search) (resp *types.Roles, err error) {
	rb := l.svcCtx.Models.Role.RowBuilder()
	rbCount := l.svcCtx.Models.Role.CountBuilder("id")
	where := struct {
		Label string `json:"label"`
	}{}
	logx.Info(req.Where)
	err = json.Unmarshal([]byte(req.Where), &where)
	if err == nil {
		rb = rb.Where("label = ?", where.Label)
		rbCount = rbCount.Where("label = ?", where.Label)
	}

	var roles []*model.AdminRole
	if req.Page == 0 && req.Size == 0 {
		roles, err = l.svcCtx.Models.Role.FindAll(l.ctx, rb, "")
	} else {
		roles, err = l.svcCtx.Models.Role.FindPageListByPage(l.ctx, rb, int64(req.Page), int64(req.Size), "")
	}

	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单查找失败%v", err)
	}

	count, err := l.svcCtx.Models.Role.FindCount(l.ctx, rbCount)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单total查找失败%v", err)
	}

	resp = &types.Roles{
		Roles:    []types.AdminRole{},
		Page:     req.Page,
		PageSize: req.Size,
		Total:    int(count),
	}

	for _, role := range roles {
		resp.Roles = append(resp.Roles, types.AdminRole{
			Id:         role.Id,
			Alias:      role.Alias,
			Label:      role.Label,
			Remark:     role.Remark,
			Status:     role.Status,
			Sort:       role.Sort,
			CreateTime: role.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return resp, nil
}
